package com.lyh.api;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

/**
 * @author SHOUSHEN.LUAN
 * @since 2023-11-16
 */
public class TimeRouter {
    private String prefix;
    private final Date minTime = getMinTime();

    private TimeRouter(String prefix) {
        this.prefix = prefix;
    }

    public static TimeRouter of(String prefix) {
        return new TimeRouter(prefix);
    }

    protected int getQuarter(LocalDate date) {
        int month = date.getMonthValue();
        if (month >= 1 && month <= 3) {
            return 1;
        } else if (month >= 4 && month <= 6) {
            return 2;
        } else if (month >= 7 && month <= 9) {
            return 3;
        } else {
            return 4;
        }
    }

    protected Date getMinTime() {
        try {
            return new SimpleDateFormat("yyyy-MM-dd").parse("2022-12-01");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public List<String> getTables() {
        LocalDate localDate = Instant.ofEpochMilli(minTime.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
        int quarter = getQuarter(localDate);
        int year = localDate.getYear();
        List<String> tables = new ArrayList<>();
        tables.add(prefix + "_" + year + quarter);
        while (localDate.isBefore(LocalDate.now())) {
            localDate = localDate.plusMonths(3);
            quarter = getQuarter(localDate);
            year = localDate.getYear();
            tables.add(prefix + "_" + year + quarter);
            if (tables.size() > 64) {
                throw new IllegalStateException("表数量超过64个");
            }
        }
        return tables;
    }

    public String getTablesAsString() {
        String[] array = getTables().stream().toArray(String[]::new);
        return String.join(",", array);
    }

    public static void main(String[] args) {
        TimeRouter timeRouter = new TimeRouter("test");
        System.out.println(Arrays.toString(timeRouter.getTables().toArray()));

    }

}
